// Redis 连接池工具类
const redisPool = require('./redisClient');

// 控制台输出颜色配置
const colors = {
    reset: '\x1b[0m',    // 重置颜色
    blue: '\x1b[34m',    // 蓝色用于连接获取提示
    magenta: '\x1b[35m', // 品红色用于连接释放提示
    gray: '\x1b[90m'     // 灰色用于时间戳显示
};

// 生成北京时间字符串（精确到毫秒）
function getBeijingTime() {
    return new Date().toLocaleString('zh-CN', {
        timeZone: 'Asia/Shanghai',          // 时区设置为上海
        year: 'numeric',                    // 四位年份
        month: '2-digit',                   // 两位月份
        day: '2-digit',                     // 两位日期
        hour: '2-digit',                    // 24小时制小时
        minute: '2-digit',                  // 两位分钟
        second: '2-digit',                  // 两位秒数
        fractionalSecondDigits: 3          // 三位毫秒
    }).replace(/(\d+)\/(\d+)\/(\d+),/, '$3-$1-$2 ')
        .replace('上午', ' ').replace('下午', ' '); // 格式化日期字符串
}

// 连接池状态追踪变量
let lastBorrowed = 0;   // 上次记录的已借出连接数
let lastAvailable = 0;   // 上次记录的可用连接数

const redisHelper = {
    /**
     * 获取键值
     * @param {string} key - 要获取的键名
     * @returns {Promise<string>} 键对应的值
     */
    async get(key) {
        const client = await redisPool.acquire()
        const currentBorrowed = redisPool.borrowed  // 当前已借出连接数
        const currentAvailable = redisPool.available // 当前可用连接数

        // 当连接池状态变化时记录日志
        if (currentBorrowed !== lastBorrowed || currentAvailable !== lastAvailable) {
            const time = getBeijingTime();
            console.log(`${colors.gray}[${time}]${colors.reset} ${colors.blue}▲ Redis连接获取 ${colors.reset}（可用: ${colors.magenta}${currentAvailable}${colors.reset} 使用中: ${colors.magenta}${currentBorrowed}${colors.reset}）`);
            lastBorrowed = currentBorrowed;
            lastAvailable = currentAvailable;
        }

        try {
            return await client.get(key)
        } finally {
            redisPool.release(client)
            const newBorrowed = redisPool.borrowed
            const newAvailable = redisPool.available

            // 连接释放时状态变化检测
            if (newBorrowed !== lastBorrowed || newAvailable !== lastAvailable) {
                const releaseTime = getBeijingTime();
                console.log(`${colors.gray}[${releaseTime}]${colors.reset} ${colors.magenta}▼ Redis连接释放 ${colors.reset}（可用: ${colors.blue}${newAvailable}${colors.reset} 使用中: ${colors.blue}${newBorrowed}${colors.reset}）`);
                lastBorrowed = newBorrowed;
                lastAvailable = newAvailable;
            }
        }
    },
    // 设置值
    async set(key, value, ttl = 0) {
        const client = await redisPool.acquire()
        const time = getBeijingTime();
        console.log(`${colors.gray}[${time}]${colors.reset} ${colors.blue}▲ Redis连接获取 ${colors.reset}（可用: ${colors.magenta}${redisPool.available}${colors.reset} 使用中: ${colors.magenta}${redisPool.borrowed}${colors.reset}）`);
        try {
            if (ttl > 0) {
                await client.set(key, value, 'EX', ttl)
            } else {
                await client.set(key, value)
            }
        } finally {
            redisPool.release(client)
            const releaseTime = getBeijingTime();
            console.log(`${colors.gray}[${releaseTime}]${colors.reset} ${colors.magenta}▼ Redis连接释放 ${colors.reset}（可用: ${colors.blue}${redisPool.available}${colors.reset} 使用中: ${colors.blue}${redisPool.borrowed}${colors.reset}）`);
        }
    },

    // 删除键
    async del(key) {
        const client = await redisPool.acquire()
        const time = getBeijingTime();
        console.log(`${colors.gray}[${time}]${colors.reset} ${colors.blue}▲ Redis连接获取 ${colors.reset}（可用: ${colors.magenta}${redisPool.available}${colors.reset} 使用中: ${colors.magenta}${redisPool.borrowed}${colors.reset}）`);
        try {
            return await client.del(key)
        } finally {
            redisPool.release(client)
            const releaseTime = getBeijingTime();
            console.log(`${colors.gray}[${releaseTime}]${colors.reset} ${colors.magenta}▼ Redis连接释放 ${colors.reset}（可用: ${colors.blue}${redisPool.available}${colors.reset} 使用中: ${colors.blue}${redisPool.borrowed}${colors.reset}）`);
        }
    },
    // 当key是menus:*时删除所有的的结构批量删除
    async delByKey(pattern) {
        const client = await redisPool.acquire();
        const time = getBeijingTime();
        console.log(`${colors.gray}[${time}]${colors.reset} ${colors.blue}▲ Redis连接获取 ${colors.reset}（可用: ${colors.magenta}${redisPool.available}${colors.reset} 使用中: ${colors.magenta}${redisPool.borrowed}${colors.reset}）`);
        try {
            let cursor = '0';
            let keys = [];

            // 使用SCAN迭代查找匹配模式的键
            do {
                const [newCursor, foundKeys] = await client.scan(
                    cursor,
                    'MATCH', pattern,
                    'COUNT', 100
                );
                cursor = newCursor;
                keys = keys.concat(foundKeys);
            } while (cursor !== '0');

            // 批量删除找到的键
            if (keys.length > 0) {
                await client.del(keys);
            }
        } finally {
            redisPool.release(client);
            const releaseTime = getBeijingTime();
            console.log(`${colors.gray}[${releaseTime}]${colors.reset} ${colors.magenta}▼ Redis连接释放 ${colors.reset}（可用: ${colors.blue}${redisPool.available}${colors.reset} 使用中: ${colors.blue}${redisPool.borrowed}${colors.reset}）`);
        }
    }
}

/**
 * 测试用方法 - 验证 Redis 连接状态
 * @returns {Promise<void>}
 */
const test = async () => {
    try {
        const title = await redisHelper.get('success')
        console.log(`${colors.gray}[${getBeijingTime()}]${colors.reset} ${colors.magenta}Redis:${colors.reset} ${colors.blue}${title}${colors.reset}`)
    } catch (error) {
        console.error(`${colors.gray}[${getBeijingTime()}]${colors.reset} ${colors.magenta}测试失败:${colors.reset} ${colors.blue}${error}${colors.reset}`)
    }
}

module.exports = {
    ...redisHelper,
    test
}
